package com.dxq.oa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Payload;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtils {

    private static final String SIGN = "oaoa";

    //获取token
    public static String getToken(Map<String,String> map){

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,30);  //设置30 分钟过期
        Date time = calendar.getTime();
        JWTCreator.Builder builder = JWT.create();

        //如果有效荷载不为空，循环赋值
        if(!map.isEmpty()){
            map.forEach((k,v)->{
                builder.withClaim(k,v);
            });
        }

        String  token = builder.withExpiresAt(time).sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    //token验证
    public static boolean verify(String token){
        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
            DecodedJWT verify = build.verify(token);
            return true;
        }catch (Exception e){
            log.info("token验证失败，错误信息为========》"+e.getMessage());
            return false;

        }

    }

    //取出token中的用户信息
    public static Payload getInfo(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode;
    }


}
